package com.zhenmaitang.clinic_sys.security;

import com.zhenmaitang.clinic_sys.service.PermissionService;
import com.zhenmaitang.clinic_sys.service.UriPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class PermissionEvaluator {
    
    @Autowired
    private PermissionService permissionService;
    
    @Autowired
    private UriPermissionService uriPermissionService;
    
    /**
     * 检查当前用户是否有指定权限
     */
    public boolean hasPermission(String permissionCode) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }
        
        String username = authentication.getName();
        return permissionService.hasPermission(username, permissionCode);
    }
    
    /**
     * 检查当前用户是否有指定资源的操作权限
     */
    public boolean hasResourcePermission(String resource, String action) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }
        
        String username = authentication.getName();
        return permissionService.hasResourcePermission(username, resource, action);
    }
    
    /**
     * 检查当前用户是否有指定权限（通过权限代码）
     */
    public boolean hasPermissionCode(String permissionCode) {
        return hasPermission(permissionCode);
    }
    
    /**
     * 检查当前用户是否有访问指定URI的权限
     */
    public boolean hasUriPermission(String uri, String method) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }
        
        // 获取当前用户ID
        Integer userId = getCurrentUserId();
        if (userId == null) {
            return false;
        }
        
        return uriPermissionService.hasUriPermission(userId, uri, method);
    }
    
    /**
     * 获取当前登录用户ID
     */
    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        
        Object principal = authentication.getPrincipal();
        if (principal instanceof CustomUserDetails) {
            return ((CustomUserDetails) principal).getUserId();
        }
        
        return null;
    }
}